<template>
  <n-grid x-gap="10" y-gap="10" :col="24">
    <n-gi :span="24">
      <div class="product-imei-wapper">
        <n-space vertical>
          <div class="variant-name">
            <span>{{ variant.name }}</span>
          </div>
          <n-form-item label="序列号" path="user.age">
            <n-input placeholder="请输入序列号" clearable v-model:value="imei">
              <template #suffix>
                <n-button quaternary circle>
                  <template #icon>
                    <n-icon :component="Copy" />
                  </template>
                </n-button>
              </template>
            </n-input>
          </n-form-item>
        </n-space>
      </div>
      <div class="mt-5">
        <div class="select-title mb-2">
          <span>问题清单</span>
        </div>
        <n-grid x-gap="10" y-gap="10" :col="24">
          <n-gi span="6">
            <div class="custom-choose-item custom-choose-item--small">
              <n-icon size="20">
                <AddOutline />
              </n-icon>
            </div>
          </n-gi>
          <n-gi
            span="6"
            v-for="question in checkList.questionItems"
            :key="question.id"
          >
            <div
              class="custom-choose-item custom-choose-item--small relative"
              :class="{
                'custom-choose-item--active': isSelected(question.id),
              }"
              @click.stop="handleSelectQuestion(question.id)"
            >
              <n-button
                size="tiny"
                class="absolute z-10 right-1 top-1"
                quaternary
                circle
                v-if="question.description"
                @click.stop="handleClickQuestionDescription(question)"
              >
                <template #icon>
                  <n-icon><InformationCircleOutline /></n-icon>
                </template>
              </n-button>
              <div class="title">
                <span> {{ question.name }} </span>
              </div>
            </div>
          </n-gi>
        </n-grid>
      </div>
      <div class="mt-5 flex justify-between items-end">
        <div>
          <n-spin :show="calculateLoading">
            <div class="select-title">
              <span>推荐回收价格：</span>
              <span>{{ currencyFormat(shownTradeinPrice) }}</span>
            </div>
          </n-spin>
          <div class="mt-2">
            <span>最后更新时间: 2024-06-03</span>
          </div>
        </div>
        <n-button type="primary" @click.stop="handleAddToCart"
          >加到回收清单</n-button
        >
      </div>
    </n-gi>
  </n-grid>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { debounce, get } from "lodash-es";
import { useModal, useMessage } from "naive-ui";
import { currencyFormat } from "@/common/utils/currencyFormatter/index.ts";
import { Copy, AddOutline, InformationCircleOutline } from "@vicons/ionicons5";
import { getCheckListByProductId } from "@/api/checkList/checkList.api";
import { calculatePrice } from "@/api/tradein/tradein.api";
import { IChooseQuestionProps } from "./props";

const emits = defineEmits(["selected"]);

const props = withDefaults(defineProps<IChooseQuestionProps>(), {
  productId: "",
  variant: {},
});

const modal = useModal();
const message = useMessage();

const initLoading = ref<boolean>(true);
const calculateLoading = ref<boolean>(false);
const checkList = ref<any>({});
const selectedChcekMap = ref<any>({});
const shownTradeinPrice = ref<number | null>(null);
const imei = ref<string>("");

const handleGetCheckList = async () => {
  initLoading.value = true;
  try {
    const res = await getCheckListByProductId({
      productId: props.productId,
    });
    checkList.value = get(res, "result") || [];
    checkList.value?.questionItems.forEach((item: any) => {
      const { id } = item;
      // 默认所有问题都补选中
      selectedChcekMap.value[id] = "0";
    });
  } finally {
    initLoading.value = false;
  }
};

const isSelected = (questionId: string) => {
  return selectedChcekMap.value[questionId] === "1";
};

const handleClickQuestionDescription = (question: any) => {
  modal.create({
    title: question.name,
    preset: "dialog",
    content: question.description,
  });
};

const handleSelectQuestion = debounce(function (questionId: string) {
  if (selectedChcekMap.value[questionId] === "0") {
    selectedChcekMap.value[questionId] = "1";
  } else {
    selectedChcekMap.value[questionId] = "0";
  }
  handleCalculatePrice();
}, 500);

const handleCalculatePrice = async () => {
  calculateLoading.value = true;
  try {
    let _selectedQuestionIds: string[] = [];
    for (const key in selectedChcekMap.value) {
      if (selectedChcekMap.value[key] && selectedChcekMap.value[key] === "1") {
        _selectedQuestionIds.push(key);
      }
    }

    if (!_selectedQuestionIds.length) {
      // 没有选中问题，显示推荐价格
      shownTradeinPrice.value = get(props.variant, "recTradeinPrice");
      return;
    }

    const params = {
      variantId: props.variant.id,
      selectedQuestionIds: _selectedQuestionIds,
    };

    const res = await calculatePrice(params);
    console.log(res);
    shownTradeinPrice.value = get(res, "result") || 0;
  } finally {
    calculateLoading.value = false;
  }
};

const handleAddToCart = () => {
  if (!imei.value) {
    message.error("请输入序列号");
    return;
  }

  emits("selected", {
    checkList: checkList.value,
    selectedChcekMap: selectedChcekMap.value,
    shownTradeinPrice: shownTradeinPrice.value,
    imei: imei.value,
  });
};

const init = () => {
  console.log(props.variant);
  shownTradeinPrice.value = get(props.variant, "recTradeinPrice");
  console.log(`shownTradeinPrice.value:${shownTradeinPrice.value}`);
  handleGetCheckList();
};

onMounted(() => {
  init();
});
</script>
<style lang="scss" scoped>
.product-imei-wapper {
  @apply rounded-lg bg-slate-100 p-2;
  .variant-name {
    font-weight: 900;
    font-size: 20px;
    color: #000;
    line-height: 34px;
  }
}
</style>
